package com.lzy.sso.client.process.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.lzy.sso.client.process.AbstractProcessService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: lzy
 * @Date: 2022/4/30 18:56
 * @Description:
 */

@Service
@ConditionalOnProperty(value = "lzy.sso-client.type",havingValue = "jwt")
public class JWTService extends AbstractProcessService {

    protected String sign(Map<String,Object> map){
        return JWT.create()
                .withPayload(map)
                .sign(Algorithm.HMAC256(properties.getJwtSecret()));
    }


    @Override
    protected void processResult(HttpServletRequest request, HttpServletResponse response, Map map) {
        boolean flag=false;
        Map<Object,Object> ret=null;
        if(map!=null) {
            Object val = map.get("val");
            if(val!=null){
                Map temp=(Map) val;
                val=temp.get("info");
                if(val!=null){
                    ret=(Map) val;
                    flag=true;
                }
            }
        }

        if(!flag){
            throw new RuntimeException("信息获取失败!");
        }

        String sign = sign(map);
        response.setHeader(properties.getJwtName(),sign);
    }

    @Override
    public boolean validate(HttpServletRequest request, HttpServletResponse response) {
        String token=request.getHeader(properties.getJwtName());
        if(token==null)
            return false;

        try {
            JWT.require(Algorithm.HMAC256(properties.getJwtName()))
                    .build()
                    .verify(token);
        } catch (Exception e){
            return false;
        }

        return true;
    }
}
